//
//  ClinicTableViewController.m
//  EcmDoctor
//
//  Created by 张进 on 15/7/13.
//  Copyright (c) 2015年 张进. All rights reserved.
//

#import "ClinicTableViewController.h"
#import "ClinicTableCell.h"
#import "AppUtils.h"
#import "MJRefresh.h"
#import "badgeUrl.h"
#import "AppDelegate.h"

@interface ClinicTableViewController () <UITableViewDataSource, UITableViewDelegate>{
    NSMutableArray *tableData;  //表格数据
}

@property (nonatomic, strong) UIButton *touchButton;
@property (nonatomic, strong) UILabel *lab;
@property (nonatomic, strong) UIView *blackView;
@property (nonatomic, assign) BOOL delete;

@end

@implementation ClinicTableViewController

- (void)viewWillAppear:(BOOL)animated {
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [AppUtils getBackground];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
//    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+49+64, kScreenWidth, kScreenHeight-64-49) style:UITableViewStylePlain];
    tableData = [[NSMutableArray alloc] init];
    //设置row的高度为自定义cell的高度
    _tableview.rowHeight = 90;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    //无分割线
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.backgroundColor = [AppUtils getBackground];
    
    self.navigationController.navigationBar.hidden = YES;
    
    //当没有数据时的提示
    _touchButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [_touchButton addTarget:self action:@selector(download) forControlEvents:UIControlEventTouchUpInside];
    
    _lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    _lab.center = CGPointMake(kScreenWidth/2, kScreenHeight/2);
    _lab.text = @"暂时没有门诊加号信息，点击刷新";
    _lab.textAlignment = NSTextAlignmentCenter;
    
    [self download];
    
    _tableview.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self download];
    }];
}

- (void)download {
    if (!_blackView) {
        _blackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    }
    _blackView.backgroundColor = [UIColor blackColor];
    _blackView.alpha = 0.3;
    [self.view addSubview:_blackView];
    NSString *doctorId = [SSKeychain passwordForService:APP_SERVICE_NAME account:APP_DOCTORINFOID_KEY];
    
    [Clinic loginWithDoctor_info_id:doctorId Isfinish:@"0" success:^(NSArray *doctor) {
        
        [_tableview.header endRefreshing];
        [tableData removeAllObjects];
        
        for (Clinic *info in doctor) {
            [tableData addObject:info];
        }
        
        [_lab removeFromSuperview];
        [_touchButton removeFromSuperview];
        if (tableData.count == 0) {
            [self.view addSubview:_lab];
            [self.view addSubview:_touchButton];
        }
        
        [_tableview reloadData];
        [_blackView removeFromSuperview];
        
    } failure:^(NSError *error) {
        [_tableview.header endRefreshing];
        [_blackView removeFromSuperview];
        NSLog(@"%@", error.localizedDescription);
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        
        //需要注意的是self.isViewLoaded是必不可少的，其他方式访问视图会导致它加载 ，在WWDC视频也忽视这一点。
        
        if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
        
    }
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated {
    
    
    //    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
//        
//        //需要注意的是self.isViewLoaded是必不可少的，其他方式访问视图会导致它加载 ，在WWDC视频也忽视这一点。
//        self.view = nil;
//        if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
//        {
//            // Add code to preserve data stored in the views that might be
//            // needed later.
//            
//            // Add code to clean up other strong references to the view in
//            // the view hierarchy.
//            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
//        }
//        
//    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return tableData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"ClinicTableCell";
    //自定义cell类
    ClinicTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        //通过xib的名称加载自定义的cell
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ClinicTableCell" owner:self options:nil] lastObject];
        
    }
    
    
    if (indexPath.row%2 == 0) {
        cell.backgroundColor = [UIColor colorWithRed:1.0 green:248.0/255.0 blue:238.0/255.0 alpha:1.0];
    }
    
    cell.clinicModel = tableData[indexPath.row];
    
    return cell;
}

//移除选中，非高亮
-(void)unselectCell:(id)sender{
    [_tableview deselectRowAtIndexPath:[_tableview indexPathForSelectedRow] animated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    Clinic *clinic = tableData[indexPath.row];
    
    if ([clinic.info_state isEqualToString:@"0"]) {
        clinic.info_state=@"1";
        [tableData replaceObjectAtIndex:indexPath.row withObject:clinic];
        //更新badge
        [badgeUrl updateOnLineStateWithmethodname:@"updateOnAddTimeState" andask_info_id:clinic.ask_info_id success:^(BOOL bl) {
            NSLog(@"success");
            [self upDateBadgemethod:@"getOnAddTimeInfoNum"];
        } failure:^(NSError *error) {
            
        }];
    }
    
    
    
    if (clinic.picUrl) {
        [self.tabBarController performSegueWithIdentifier:@"showClinicContrillerDetail" sender:@{@"name":clinic.name, @"sex":clinic.sex, @"content":clinic.content,@"voiceUrl":clinic.voiceUrl, @"age":clinic.age, @"picUrl":clinic.picUrl, @"headImage":clinic.icon_Url, @"info":[NSString stringWithFormat:@"患者已经预约了 %@ %@ %@的门诊加号", clinic.info_order_date, [AppUtils weekForClinic:clinic.info_order_week], clinic.info_order_time], @"doctorId":[SSKeychain passwordForService:APP_SERVICE_NAME account:APP_DOCTORINFOID_KEY], @"askId":clinic.ask_info_id}];
    } else {
        [self.tabBarController performSegueWithIdentifier:@"showClinicContrillerDetail" sender:@{@"name":clinic.name, @"sex":clinic.sex, @"content":clinic.content, @"voiceUrl":clinic.voiceUrl, @"age":clinic.age, @"headImage":clinic.icon_Url, @"info":[NSString stringWithFormat:@"患者已经预约了 %@ %@ %@的门诊加号", clinic.info_order_date, [AppUtils weekForClinic:clinic.info_order_week], clinic.info_order_time], @"doctorId":[SSKeychain passwordForService:APP_SERVICE_NAME account:APP_DOCTORINFOID_KEY], @"askId":clinic.ask_info_id}];
    }
    
    ClinicTableCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.isRead.alpha = 0;
    
//    [self.tabBarController performSegueWithIdentifier:@"showQuestionNoRelyDetail" sender:self];
    //移除选中，非高亮
    [self performSelector:@selector(unselectCell:) withObject:nil afterDelay:0.5];
}

#pragma mark 更新badge值
- (void)upDateBadgemethod:(NSString *)method {
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    NSString *docId = [SSKeychain passwordForService:APP_SERVICE_NAME account:APP_DOCTORINFOID_KEY];
    [badgeUrl badgeWithdoctor_info_id:docId moduleName:@"DoctorRS" methodname:method success:^(NSString *badgeNumber) {
        app.clinicBadge.text = badgeNumber;  
        
        
    } failure:^(NSError *error) {
        
    }];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
